/**
 * 
 */
package speculoos.jndi.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * A sample converter for transforming array of bytes into an arbitrary class
 * instance. This class demonstrates the usage of the IO API by allowing
 * instanciation of arbitrary objects from byte streams and serialization back
 * to byte[]. The class of the object must implements properly the
 * {@link java.io.Serializable} interface or else an error will occur.
 * 
 * @author abailly
 */
public class SerializableIO implements ObjectIO {

	private static byte[] sample = new byte[0];

	/*
	 * (non-Javadoc)
	 * 
	 * @see fr.norsys.mapper.jndi.io.ObjectIO#toLDAP(java.lang.Object)
	 */
	public Object toLDAP(Object o) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream dos = new ObjectOutputStream(bos);
		dos.writeObject(o);
		dos.flush();
		dos.close();
		bos.close();
		return bos.toByteArray();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see fr.norsys.mapper.jndi.io.ObjectIO#fromLDAP(java.lang.Class,
	 *      java.lang.Object)
	 */
	public Object fromLDAP(Class c, Object o) throws IOException {
		/* convert from byte arrays into arbitrary object */
		byte[] bytes = (byte[]) o;
		ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(bis);
		Object ser;
		try {
			ser = ois.readObject();
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException(
					"Cannot find class for deserializing object");
		}
		if (!c.isAssignableFrom(ser.getClass()))
			throw new IllegalArgumentException("Bad target class");
		return ser;
	}
}
